<template>
  <div class="bg-white rounded-lg shadow-sm">
    <div class="p-4 border-b border-gray-200">
      <div class="flex items-center justify-between">
        <h3 class="text-lg font-semibold text-gray-900">车辆管理表格</h3>
        <div class="flex space-x-2">
          <el-input
              v-model="searchQuery"
              placeholder="搜索车辆ID/车型/车队"
              clearable
              style="width: 240px"
              @clear="handleSearchClear"
              @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" size="small" @click="showAddModal = true">
            <el-icon><Plus /></el-icon>
            添加车辆
          </el-button>
          <el-button
              type="danger"
              size="small"
              :disabled="!hasSelectedVehicles"
              @click="handleBatchDelete"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button
              type="warning"
              size="small"
              :disabled="!hasSelectedVehicles"
              @click="showBatchEditModal = true"
          >
            <el-icon><Edit /></el-icon>
            批量编辑
          </el-button>
        </div>
      </div>
    </div>

    <el-table 
      :data="vehicles" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
      max-height="600"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column prop="id" label="车辆ID" />
      
      <el-table-column prop="model" label="车型" width="120" />
      
      <el-table-column prop="fleet" label="所属车队" width="100" />
      
      <el-table-column prop="soc" label="SOC" width="80">
        <template #default="{ row }">
          <span :class="getSocColor(row.soc)">{{ row.soc }}%</span>
        </template>
      </el-table-column>
      
      <el-table-column prop="temperature" label="温度" width="80">
        <template #default="{ row }">
          {{ row.temperature }}℃
        </template>
      </el-table-column>
      
      <el-table-column prop="riskLevel" label="风险等级" width="100">
        <template #default="{ row }">
          <el-tag :type="getRiskTagType(row.riskLevel)" size="small">
            {{ getRiskText(row.riskLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="热工况向量" width="150">
        <template #default="{ row }">
          <span class="font-mono text-sm">
            [{{ row.thmVector.map(v => v.toFixed(2)).join(',') }}]
          </span>
        </template>
      </el-table-column>
      
      <el-table-column prop="lastUpdate" label="最后更新" width="250" />
      
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleView(row)">
            查看
          </el-button>
          <el-button type="warning" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加车辆弹窗 -->
    <el-dialog v-model="showAddModal" title="添加车辆" width="600px">
      <el-form :model="newVehicle" :rules="vehicleRules" ref="addFormRef" label-width="120px">
        <el-form-item label="车辆ID" prop="id">
          <el-input v-model="newVehicle.id" placeholder="请输入车辆ID" />
        </el-form-item>
        <el-form-item label="车型" prop="model">
          <el-select v-model="newVehicle.model" placeholder="请选择车型">
            <el-option label="BYD Han EV" value="BYD Han EV" />
            <el-option label="Tesla Model 3" value="Tesla Model 3" />
            <el-option label="NIO ES6" value="NIO ES6" />
            <el-option label="XPeng P7" value="XPeng P7" />
            <el-option label="Geely GE11" value="Geely GE11" />
            <el-option label="Aion S" value="Aion S" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属车队" prop="fleet">
          <el-select v-model="newVehicle.fleet" placeholder="请选择车队">
            <el-option label="车队A" value="车队A" />
            <el-option label="车队B" value="车队B" />
            <el-option label="车队C" value="车队C" />
          </el-select>
        </el-form-item>
        <el-form-item label="SOC" prop="soc">
          <el-input-number v-model="newVehicle.soc" :min="0" :max="100" :precision="1" />
          <span class="ml-2 text-gray-500">%</span>
        </el-form-item>
        <el-form-item label="温度" prop="temperature">
          <el-input-number v-model="newVehicle.temperature" :min="0" :max="50" :precision="1" />
          <span class="ml-2 text-gray-500">℃</span>
        </el-form-item>
        <el-form-item label="放电时长" prop="dischargeTime">
          <el-input-number v-model="newVehicle.dischargeTime" :min="0" :max="60" />
          <span class="ml-2 text-gray-500">分钟</span>
        </el-form-item>
        <el-form-item label="最大功率" prop="maxPower">
          <el-input-number v-model="newVehicle.maxPower" :min="0" :max="30" :precision="1" />
          <span class="ml-2 text-gray-500">kW</span>
        </el-form-item>
        <el-form-item label="当前电流" prop="current">
          <el-input-number v-model="newVehicle.current" :min="-30" :max="30" :precision="1" />
          <span class="ml-2 text-gray-500">A</span>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="newVehicle.riskLevel" placeholder="请选择风险等级">
            <el-option label="低风险" value="low" />
            <el-option label="风险预警" value="warning" />
            <el-option label="高风险" value="high" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showAddModal = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">确认添加</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑车辆弹窗 -->
    <el-dialog v-model="showEditModal" title="编辑车辆" width="600px">
      <el-form :model="editVehicle" :rules="vehicleRules" ref="editFormRef" label-width="120px">
        <el-form-item label="车辆ID" prop="id">
          <el-input v-model="editVehicle.id" disabled />
        </el-form-item>
        <el-form-item label="车型" prop="model">
          <el-select v-model="editVehicle.model" placeholder="请选择车型">
            <el-option label="BYD Han EV" value="BYD Han EV" />
            <el-option label="Tesla Model 3" value="Tesla Model 3" />
            <el-option label="NIO ES6" value="NIO ES6" />
            <el-option label="XPeng P7" value="XPeng P7" />
            <el-option label="Geely GE11" value="Geely GE11" />
            <el-option label="Aion S" value="Aion S" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属车队" prop="fleet">
          <el-select v-model="editVehicle.fleet" placeholder="请选择车队">
            <el-option label="车队A" value="车队A" />
            <el-option label="车队B" value="车队B" />
            <el-option label="车队C" value="车队C" />
          </el-select>
        </el-form-item>
        <el-form-item label="SOC" prop="soc">
          <el-input-number v-model="editVehicle.soc" :min="0" :max="100" :precision="1" />
          <span class="ml-2 text-gray-500">%</span>
        </el-form-item>
        <el-form-item label="温度" prop="temperature">
          <el-input-number v-model="editVehicle.temperature" :min="0" :max="50" :precision="1" />
          <span class="ml-2 text-gray-500">℃</span>
        </el-form-item>
        <el-form-item label="放电时长" prop="dischargeTime">
          <el-input-number v-model="editVehicle.dischargeTime" :min="0" :max="60" />
          <span class="ml-2 text-gray-500">分钟</span>
        </el-form-item>
        <el-form-item label="最大功率" prop="maxPower">
          <el-input-number v-model="editVehicle.maxPower" :min="0" :max="30" :precision="1" />
          <span class="ml-2 text-gray-500">kW</span>
        </el-form-item>
        <el-form-item label="当前电流" prop="current">
          <el-input-number v-model="editVehicle.current" :min="-30" :max="30" :precision="1" />
          <span class="ml-2 text-gray-500">A</span>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="editVehicle.riskLevel" placeholder="请选择风险等级">
            <el-option label="低风险" value="low" />
            <el-option label="风险预警" value="warning" />
            <el-option label="高风险" value="high" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showEditModal = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">确认修改</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量编辑弹窗 -->
    <el-dialog v-model="showBatchEditModal" title="批量编辑" width="500px">
      <el-form :model="batchEditData" label-width="120px">
        <el-form-item label="所属车队">
          <el-select v-model="batchEditData.fleet" placeholder="请选择车队" clearable>
            <el-option label="车队A" value="车队A" />
            <el-option label="车队B" value="车队B" />
            <el-option label="车队C" value="车队C" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级">
          <el-select v-model="batchEditData.riskLevel" placeholder="请选择风险等级" clearable>
            <el-option label="低风险" value="low" />
            <el-option label="风险预警" value="warning" />
            <el-option label="高风险" value="high" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="mb-4 p-3 bg-blue-50 rounded-lg">
        <div class="text-sm text-blue-800">
          将对 {{ selectedVehicles.length }} 辆车辆进行批量修改
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showBatchEditModal = false">取消</el-button>
          <el-button type="primary" @click="handleBatchEdit">确认修改</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="showDetailModal" title="车辆详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="车辆ID">{{ currentVehicle.id }}</el-descriptions-item>
        <el-descriptions-item label="车型">{{ currentVehicle.model }}</el-descriptions-item>
        <el-descriptions-item label="所属车队">{{ currentVehicle.fleet }}</el-descriptions-item>
        <el-descriptions-item label="SOC">
          <span :class="getSocColor(currentVehicle.soc)">{{ currentVehicle.soc }}%</span>
        </el-descriptions-item>
        <el-descriptions-item label="温度">{{ currentVehicle.temperature }}℃</el-descriptions-item>
        <el-descriptions-item label="风险等级">
          <el-tag :type="getRiskTagType(currentVehicle.riskLevel)" size="small">
            {{ getRiskText(currentVehicle.riskLevel) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="放电时长">{{ currentVehicle.dischargeTime }}分钟</el-descriptions-item>
        <el-descriptions-item label="最大功率">{{ currentVehicle.maxPower }}kW</el-descriptions-item>
        <el-descriptions-item label="当前电流">{{ currentVehicle.current }}A</el-descriptions-item>
        <el-descriptions-item label="热工况向量" :span="2">
          <span class="font-mono text-sm">
            [{{ currentVehicle.thmVector?.map(v => v.toFixed(2)).join(',') }}]
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="最后更新" :span="2">{{ currentVehicle.lastUpdate }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="flex justify-end">
          <el-button type="primary" @click="showDetailModal = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAppStore } from '@/stores'
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Vehicle } from '@/stores'

const store = useAppStore()

const showAddModal = ref(false)
const showEditModal = ref(false)
const showBatchEditModal = ref(false)
const selectedVehicles = ref<Vehicle[]>([])
const searchQuery = ref('')
const currentVehicle = ref<Vehicle>({} as Vehicle)
const filteredVehicles = computed(() => {
  if (!searchQuery.value) return store.vehicles

  const query = searchQuery.value.toLowerCase()
  return store.vehicles.filter(vehicle =>
      vehicle.id.toLowerCase().includes(query) ||
      vehicle.model.toLowerCase().includes(query) ||
      vehicle.fleet.toLowerCase().includes(query)
  )
})

const handleSearch = () => {
  // Search is handled automatically by filteredVehicles computed property
}

const handleSearchClear = () => {
  searchQuery.value = ''
}
const showDetailModal = ref(false)

const handleView = (vehicle: Vehicle) => {
  currentVehicle.value = { ...vehicle }
  showDetailModal.value = true
}

const newVehicle = ref({
  id: '',
  model: '',
  fleet: '',
  soc: 50,
  temperature: 25,
  dischargeTime: 10,
  maxPower: 15,
  current: -8,
  riskLevel: 'low' as 'low' | 'warning' | 'high',
  thmVector: [0.5, 0.5, 0.5] as [number, number, number],
  lastUpdate: new Date().toLocaleString('zh-CN')
})

const editVehicle = ref<Vehicle>({} as Vehicle)

const batchEditData = ref({
  fleet: '',
  riskLevel: ''
})

const vehicleRules = {
  id: [{ required: true, message: '请输入车辆ID', trigger: 'blur' }],
  model: [{ required: true, message: '请选择车型', trigger: 'change' }],
  fleet: [{ required: true, message: '请选择车队', trigger: 'change' }],
  soc: [{ required: true, message: '请输入SOC', trigger: 'blur' }],
  temperature: [{ required: true, message: '请输入温度', trigger: 'blur' }],
  dischargeTime: [{ required: true, message: '请输入放电时长', trigger: 'blur' }],
  maxPower: [{ required: true, message: '请输入最大功率', trigger: 'blur' }],
  current: [{ required: true, message: '请输入当前电流', trigger: 'blur' }],
  riskLevel: [{ required: true, message: '请选择风险等级', trigger: 'change' }]
}

const vehicles = computed(() => store.vehicles)
const hasSelectedVehicles = computed(() => selectedVehicles.value.length > 0)

const addFormRef = ref()
const editFormRef = ref()

const getSocColor = (soc: number) => {
  if (soc < 30) return 'text-red-600'
  if (soc < 60) return 'text-yellow-600'
  return 'text-green-600'
}

const getRiskTagType = (riskLevel: string) => {
  switch (riskLevel) {
    case 'high': return 'danger'
    case 'warning': return 'warning'
    case 'low': return 'success'
    default: return 'info'
  }
}

const getRiskText = (riskLevel: string) => {
  switch (riskLevel) {
    case 'high': return '高风险'
    case 'warning': return '风险预警'
    case 'low': return '低风险'
    default: return '未知'
  }
}

const calculateThmVector = (vehicle: any): [number, number, number] => {
  const tempNorm = (vehicle.temperature - 10) / (40 - 10)
  const timeNorm = vehicle.dischargeTime / 60
  const powerNorm = vehicle.maxPower / 25
  return [
    Math.round(tempNorm * 100) / 100,
    Math.round(timeNorm * 100) / 100,
    Math.round(powerNorm * 100) / 100
  ]
}

const handleSelectionChange = (selection: Vehicle[]) => {
  selectedVehicles.value = selection
}

// const handleView = (vehicle: Vehicle) => {
//   store.setCurrentVehicle(vehicle)
//   ElMessage.success(`已选择车辆 ${vehicle.id}`)
// }

const handleEdit = (vehicle: Vehicle) => {
  editVehicle.value = { ...vehicle }
  showEditModal.value = true
}

const handleDelete = async (vehicle: Vehicle) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除车辆 ${vehicle.id} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    store.deleteVehicle(vehicle.id)
    ElMessage.success('删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleAdd = async () => {
  try {
    await addFormRef.value.validate()
    
    const vehicleData = {
      ...newVehicle.value,
      thmVector: calculateThmVector(newVehicle.value),
      lastUpdate: new Date().toLocaleString('zh-CN')
    }
    
    store.addVehicle(vehicleData)
    showAddModal.value = false
    
    // 重置表单
    newVehicle.value = {
      id: '',
      model: '',
      fleet: '',
      soc: 50,
      temperature: 25,
      dischargeTime: 10,
      maxPower: 15,
      current: -8,
      riskLevel: 'low',
      thmVector: [0.5, 0.5, 0.5],
      lastUpdate: new Date().toLocaleString('zh-CN')
    }
    
    ElMessage.success('添加成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleUpdate = async () => {
  try {
    await editFormRef.value.validate()
    
    const updates = {
      ...editVehicle.value,
      thmVector: calculateThmVector(editVehicle.value),
      lastUpdate: new Date().toLocaleString('zh-CN')
    }
    
    store.updateVehicle(editVehicle.value.id, updates)
    showEditModal.value = false
    ElMessage.success('修改成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedVehicles.value.length} 辆车辆吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    selectedVehicles.value.forEach(vehicle => {
      store.deleteVehicle(vehicle.id)
    })
    
    selectedVehicles.value = []
    ElMessage.success('批量删除成功')
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleBatchEdit = () => {
  const updates: Partial<Vehicle> = {}
  
  if (batchEditData.value.fleet) {
    updates.fleet = batchEditData.value.fleet
  }
  
  if (batchEditData.value.riskLevel) {
    updates.riskLevel = batchEditData.value.riskLevel as 'low' | 'warning' | 'high'
  }
  
  selectedVehicles.value.forEach(vehicle => {
    store.updateVehicle(vehicle.id, {
      ...updates,
      lastUpdate: new Date().toLocaleString('zh-CN')
    })
  })
  
  showBatchEditModal.value = false
  batchEditData.value = { fleet: '', riskLevel: '' }
  ElMessage.success(`已批量修改 ${selectedVehicles.value.length} 辆车辆`)
}
</script>